package manager;

import java.util.*;

import org.hibernate.Session;

import dao.*;
import model.*;
import util.HibernateSessionFactory;

/**
 * managing tag, using singleton
 * 
 * @author xbingo
 * 
 */
public class TagManager {
	private static TagDAO tagDao = new TagDAO();
	private static TagManager tagManager = null;

	private TagManager() {

	}

	/**
	 * get the instance of TagManager
	 * 
	 * @return
	 */
	public static TagManager getTagManager() {
		if (tagManager == null)
			tagManager = new TagManager();
		return tagManager;
	}

	/**
	 * get the instance of TagDAO
	 * 
	 * @return
	 */
	public TagDAO getTagDAO() {
		return this.tagDao;
	}

	/**
	 * 
	 * @param user
	 * @param tagName
	 * @throws UserNotFoundException
	 */
	public void newTag(User user, String tagName) throws UserNotFoundException {
		UserManager userManager = UserManager.getUserManager();
		User u = userManager.find(user.getUsername());
		if (u == null) {
			throw new UserNotFoundException();
		}
		Tag tag = find(user, tagName);
		if (tag != null) {
			return;
		}
		tag = new Tag();
		tag.setName(tagName);
		tag.setUser(user);
		u.getTags().add(tag);
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		tagDao.save(tag);
		userManager.getUserDAO().attachDirty(u);
		session.getTransaction().commit();
	}

	/**
	 * find tag by user and tagName
	 * 
	 * @param user
	 * @param tagName
	 * @return
	 * @throws UserNotFoundException
	 */
	public Tag find(User user, String tagName) throws UserNotFoundException {
		UserManager userManager = UserManager.getUserManager();
		User u = userManager.find(user.getUsername());
		if (u == null) {
			throw new UserNotFoundException();
		}
		List<Tag> list = tagDao.findByName(tagName);
		Tag tag = null;
		for (Tag t : list) {
			if (t.getUser().getId().equals(user.getId())) {
				tag = t;
				break;
			}
		}
		return tag;
	}

	/**
	 * rename a tag from oldName to newName
	 * @param user
	 * @param oldName
	 * @param newName
	 * @throws UserNotFoundException
	 */
	public void rename(User user, String oldName, String newName)
			throws UserNotFoundException {
		Tag tag = find(user, oldName);
		tag.setName(newName);
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		tagDao.attachDirty(tag);
		session.getTransaction().commit();
	}
}
